import i18n from '../core/i18n'
import Query from '../core/db/mysql/query'
import {db} from '../core/db/mysql/db'

export function login(target, name, descriptor){
    const method = descriptor.value
    descriptor.value = function (...args) {
        if(this.session.userid) {
            return method.apply(this, args)
        }else {
            console.log('headers====>', this.ctx.headers);
            return this.setCode(-401).setMsg(i18n.login_fail).json();
            // if(this.ctx.headers['X-Requested-With'] === 'XMLHttpRequest') {
            //     console.log('XMLHttpRequest')
            //     return this.setCode(-401).setMsg(i18n.login_fail).json()
            // }else {
            //     console.log('redirect')
            //     this.redirect('/login')
            // }

        }
    }
}


export function auth(target, name, descriptor){
    const method = descriptor.value = async function(...args) {
        if(this.session.userid) {
            let cnt = await db(async conn =>{
                let Menu = new Query(conn, 'sy_menu'),
                    menus = await Menu.alias('m').fields('count(1) as cnt')
                        .join('sys_auth_record ar', 'ar.menu_id = m.id', 'LEFT')
                        .join('sys_user_auth ua','ua.auth_id = ar.auth_id','LEFT')
                        .where('ua.user_id', this.session.userid)
                        .where('m.rule', this.ctx.path)
                        .where('m.status', 1)
                        .select()
                return menus[0].cnt
            })
            return cnt <= 0?this.setCode(-403).setMsg(i18n.auth_error).json():method.apply(this, args)
        }else {
            return this.setCode(-401).setMsg(i18n.login_fail).json()
        }
    }
}
